package cn.tedu.csmall.sso.controller;

import cn.tedu.csmall.commons.pojo.admin.dto.AdminAddDTO;
import cn.tedu.csmall.commons.pojo.admin.dto.AdminLoginDTO;
import cn.tedu.csmall.commons.pojo.admin.vo.AdminListVO;
import cn.tedu.csmall.commons.restful.JsonResult;
import cn.tedu.csmall.sso.service.IAdminService;
import cn.tedu.csmall.sso.utils.AdminUserDetails;
import cn.tedu.csmall.sso.utils.LoginPrincipal;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/admins")
@Api(tags = "管理员管理模块")
@Slf4j
public class AdminController {
    @Autowired
    private IAdminService adminService;

    @ApiOperation("添加管理员")
    @PostMapping("/add-new")
    @PreAuthorize("hasAuthority('/ams/admin/update')")
    public JsonResult addNew(@RequestBody AdminAddDTO adminAddDTO){
        adminService.addNew(adminAddDTO);
        return JsonResult.ok("添加管理员成功");
    }

    @GetMapping("/list")
    @ApiOperation("查询管理员列表")
    @PreAuthorize("hasAuthority('/ams/admin/read')")
    public JsonResult<List<AdminListVO>> getListAdmins(@AuthenticationPrincipal LoginPrincipal loginPrincipal){

        Long id = loginPrincipal.getId();
        log.info("从认证信息中获取当前登陆的管理员ID:{}",id);

        List<AdminListVO> adminListVOS = adminService.list();
        return JsonResult.ok("查询管理员列表成功",adminListVOS);
    }

    //请求登陆的方法
    @ApiOperation("管理员登陆")
    @PostMapping("/login")
    public JsonResult login(@RequestBody AdminLoginDTO adminLoginDTO){
        log.info("接收到的请求参数：{}",adminLoginDTO);
        //调用service方法处理登陆
        String jwt = adminService.login(adminLoginDTO);
        return JsonResult.ok("登陆成功",jwt);

    }
}